<?php

class Admin_ListasimuladoController extends App_Controller_Action
{

    private $_table     = 'LISTA_SIMULADO';
    private $_pk        = 'LTS_ID';
    private $_order_col = 'LTS_ID';
    private $_order     = 'DESC';
    private $_sta_col   = 'LTS_STA';
    private $obj        = '';
    private $form       = '';
    private $_file_col  = 'LTS_FILE'; 
    public  $dir = 'public/upload//';
    public  $db = '';
    
    public function init()
    {
        if($this->getRequest()->getActionName() == 'edit') $this->form = new Admin_Form_Listasimulado();        
    }

    public function indexAction() {
        
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('dominio','library');
        
        $where = $this->_pk.' > 0 ';
        
        $filtro_nm = $this->_getParam('filtro_nm', '');
        
        if($filtro_nm != '') $where .= ' and LTS_NOM like "%' . $filtro_nm.'%"';
        
        $this->view->filtro_nm = $filtro_nm;
        
        $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$where.' ORDER BY '.$this->_order_col.' '.$this->_order;
        $result = $this->db->fetchAll($query);
        $this->view->result = $this->paginacao($result);
        
    }
    
    public function editAction() {
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskMoney.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskedinput.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/mask.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_form_pdr.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_listasimulado.js?1='.rand(99,9999));
        
        
        Zend_Loader::loadClass('imagem','library');
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('dominio','library');
        
        $html2 = '';
        $arr_qst = dominio::alternativasLista();
        $num_qst = 'I999F';
        foreach($arr_qst as $key => $qst){
            $html2 .= '<input type="radio" id="'.$num_qst.''.$key.'" class="rd_qst_alt" name="a['.$num_qst.']" value="'.$key.'" >';
            $html2 .= ' &nbsp; <label for="'.$num_qst.''.$key.'"><span class="btn_qst_alt qst'.$num_qst.'" qst="'.$num_qst.'" val="'.$key.'">'.$qst.'</span></label> &nbsp; ';
        }
        echo '<script> var rd_itg = \''.$html2.'\' </script>';
        
        $tpo = 1;
        echo '<script> var tpo = '.$tpo.'; </script>';
        $arr_tpo = dominio::tipoAlternativa();
        $cmb_tpo = '<select name="tpo_res[]" class="tam_med tpo_res" >';
        foreach($arr_tpo as $key => $a_tpo){
            $selected = $tpo == $key ? 'selected="selected"':'';
            $cmb_tpo .= '<option '.$selected.' value="'.$key.'">'.$a_tpo.'</option>';
        }
        $cmb_tpo .= '</select>';
        echo '<script> var cmb_tpo = \''.$cmb_tpo.'\' </script>';
        
        $query = 'SELECT SQL_CACHE DCP_ID,DCP_NOM FROM DISCIPLINA WHERE DCP_STA = 1 ORDER BY DCP_NOM';
        $result = $this->db->fetchAll($query);
        $cmb_dis = '<select name="d[]" class="tam_med_g dis_qst" ><option value="">Disciplina</option>';
        foreach($result as $row){
            $cmb_dis .= '<option value="'.$row['DCP_ID'].'">'.$row['DCP_NOM'].'</option>';
        }
        $cmb_dis .= '</select>';
        echo '<script> var cmb_dis = \''.$cmb_dis.'\' </script>';
        
        
        $arr_tpo = dominio::tipoAlternativa();
        $new_array = '""';
        foreach($arr_tpo as $key_tpo => $a_tpo) $new_array .= ',""';
        echo '<script> var rd_itg = new Array('.$new_array.'); </script>';
        foreach($arr_tpo as $key_tpo => $a_tpo){
            $html2 = '';
            //$arr_qst = dominio::alternativasLista();
            $num_qst = 'I999F';
            $arr_qst = dominio::getAlternativa($key_tpo);
            //$num_qst = 'I'.$key_tpo.'F';
            if(is_array($arr_qst)){
                foreach($arr_qst as $key => $qst){
                    $html2 .= '<input type="radio" id="'.$num_qst.''.$key.'" class="rd_qst_alt" name="a['.$num_qst.']" value="'.$key.'" >';
                    $html2 .= ' &nbsp; <label for="'.$num_qst.''.$key.'"><span class="btn_qst_alt qst'.$num_qst.'" qst="'.$num_qst.'" val="'.$key.'">'.$qst.'</span></label> &nbsp; ';
                }
            }else if($key_tpo == 3){
                $html2 .= '<input type="text" id="'.$num_qst.''.$key.'" class="num_int numero" maxlength="3" name="a['.$num_qst.']" value="" >';
            }
            
            echo '<script> rd_itg['.$key_tpo.'] = \''.$html2.'\'; </script>';
            
        }
        
        $this->view->form = $this->form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                
                $query = 'SELECT SQL_CACHE PLS_ID FROM PUBLICACAO_SIMULADO '
                        .' WHERE LTS_ID = '.$formData[$this->_pk].' ORDER BY PLS_DAT DESC';
                
                $pub = $this->db->fetchRow($query);
                $list = FALSE;
                $msg = 'Lista encerrada. Não pode ser alterada!'; 
                if($pub['PLS_ID'] > 0){
                    $list = $this->validaencerramento($pub['PLS_ID']);
                }
                
                if($this->form->isValid($formData) && $list == FALSE) {
                    
                    $id = (int) $this->form->getValue($this->_pk);
                    
                    $data = $this->form->getValues();
                    
                    unset($data['html']);
                    unset($data['submit']);
                    unset($data['q']);
                    unset($data['a']);
                    unset($data['d']);
                    unset($data['tpo_res']);
                    
                    //echo '<pre>';print_r($formData['q']);exit();
                    
                    //print_r($formData); //exit();
                    $this->db->beginTransaction();
                    if($id == 0){
                        
                        $query = 'SELECT SQL_CACHE f.* FROM FACULDADE_PROVA_DISC f, DISCIPLINA d '
                                .' WHERE f.DCP_ID = d.DCP_ID AND FAP_ID = '.$formData['FAP_ID']
                                .' AND d.DCP_STARED = 1';
                        $red = $this->db->fetchRow($query);
                        if($red['DCP_ID'] > 0){
                            $data['LTS_REDID'] = $red['DCP_ID'];
                            $data['LTS_REDNQU'] = $red['FPD_NQU'];
                            $data['LTS_REDPES'] = $red['FPD_PES'];
                        }
                        //print_r($data);
                        $data[$this->_sta_col] = 1;
                        $this->db->insert($this->_table, $data);
                        $id =  $this->db->lastInsertId();   
                        
                        $this->db->delete('LISTA_SIMULADO_GABARITO',$this->_pk.' = ' . $id);
                        
                        if(isset($formData['q']))
                        foreach($formData['q'] as $key => $q){
                            // para numero ficar inteiro
                            if($formData['tpo_res'][$key] == 3) $formData['a'][$key] = (int) $formData['a'][$key];
                            
                            $data2 = array(
                                'LTS_ID'    => $id,
                                'LSG_QST'   => $formData['q'][$key],// $q, 
                                'LSG_ALT'   => strtoupper($formData['a'][$q]),
                                'DCP_ID'    => $formData['d'][$key],
                                'LSG_TPO'    => $formData['tpo_res'][$key],
                                'LSG_STALNGETG' => $formData['stalngetg'][$key],
                                'LSG_PES' => $formData['pes'][$key],
                            );
                            
                            if(isset($formData['a'][$q.'_'.$formData['d'][$key]]))
                                    $data2['LSG_ALT'] = strtoupper($formData['a'][$q.'_'.$formData['d'][$key]]);
                            
                            $this->db->insert('LISTA_SIMULADO_GABARITO',$data2);
                        }
                    }
                    else { 
                        
                        $query = 'SELECT SQL_CACHE f.* FROM FACULDADE_PROVA_DISC f, DISCIPLINA d '
                                .' WHERE f.DCP_ID = d.DCP_ID AND FAP_ID = '.$formData['FAP_ID']
                                .' AND d.DCP_STARED = 1';
                        $red = $this->db->fetchRow($query);
                        if($red['DCP_ID'] > 0){
                            $data['LTS_REDID'] = $red['DCP_ID'];
                            $data['LTS_REDNQU'] = $red['FPD_NQU'];
                            $data['LTS_REDPES'] = $red['FPD_PES'];
                        }
                        
                        $data[$this->_sta_col] = $this->form->getValue($this->_sta_col,0);
                        $this->db->update($this->_table, $data,$this->_pk.' = ' . $id);
                        
                        foreach($formData['q'] as $key => $q){
                            // para numero ficar inteiro
                            if($formData['tpo_res'][$key] == 3) $formData['a'][$q] = (int) $formData['a'][$q];
                            
                            $query = 'SELECT SQL_CACHE * FROM LISTA_SIMULADO_GABARITO '
                                    .' WHERE LSG_QST = '.$q.' AND '.$this->_pk.' = '.$id
                                    .' AND DCP_ID = '.$formData['d'][$key];
                            $row = $this->db->fetchRow($query);
                            if($row['LSG_ID'] > 0){
                                $upd = array(
                                        'DCP_ID'    => $formData['d'][$key],
                                        'LSG_ALT' => strtoupper($formData['a'][$row['LSG_ID']]), // strtoupper($formData['a'][$q])
                                        'LSG_TPO'    => $formData['tpo_res'][$key],
                                        'LSG_STALNGETG' => $formData['stalngetg'][$key],
                                        'LSG_PES' => $formData['pes'][$key],
                                    );
                                
                                $this->db->update('LISTA_SIMULADO_GABARITO', $upd, 'LSG_QST = '.$q.' AND '.$this->_pk.' = '.$id.' AND DCP_ID = '.$formData['d'][$key]);
                            
                                $query = 'SELECT SQL_CACHE * FROM PUBLICACAO_SIMULADO'
                                        .' WHERE '.$this->_pk.' = '.$id.' ORDER BY PLS_DAT DESC';
                                
                                $pub = $this->db->fetchRow($query);
                                if($pub['PLS_ID'] > 0){
                                    
                                    $query = 'SELECT SQL_CACHE * FROM PUBLICACAO_SIMULADO_GABARITO '
                                        .' WHERE PSG_QST ='.$q.' AND PLS_ID = '.$pub['PLS_ID']
                                        .' AND DCP_ID = '.$formData['d'][$key];
                                    $pub2 = $this->db->fetchRow($query);
                                    if($pub2['PSG_ID'] > 0){
                                        $upd = array(
                                            'PSG_ALT' => strtoupper($formData['a'][$row['LSG_ID']]), // strtoupper($formData['a'][$q]),
                                            'DCP_ID'  => $formData['d'][$key],
                                            'PSG_TPO' => $formData['tpo_res'][$key],
                                            'PSG_STALNGETG' => $formData['stalngetg'][$key],
                                            'PSG_PES' => $formData['pes'][$key],
                                        );

                                        $this->db->update('PUBLICACAO_SIMULADO_GABARITO',$upd,' PSG_QST = '.$q.' AND PLS_ID = '.$pub['PLS_ID'].' AND DCP_ID = '.$formData['d'][$key]); 
                                    }else{
                                        $arr = array(
                                            'PLS_ID'  => $pub['PLS_ID'],
                                            'PSG_QST' => $q,
                                            'PSG_ALT' => strtoupper($formData['a'][$row['LSG_ID']]), // strtoupper($formData['a'][$q]),
                                            'DCP_ID'  => $formData['d'][$key],
                                            'PSG_TPO' => $formData['tpo_res'][$key],
                                            'PSG_STALNGETG' => $formData['stalngetg'][$key],
                                            'PSG_PES' => $formData['pes'][$key],
                                        );
                                        $this->db->insert('PUBLICACAO_SIMULADO_GABARITO',$arr);
                                        //print_r($arr);
                                    }
                                    
                                }
                            
                            } else{
                                
                                $data2 = array(
                                    'LTS_ID'    => $id,
                                    'LSG_QST'   => $q,
                                    'LSG_ALT'   => strtoupper($formData['a'][$q.'_'.$formData['d'][$key]]),
                                    'DCP_ID'    => $formData['d'][$key],
                                    'LSG_TPO'    => $formData['tpo_res'][$key],
                                    'LSG_STALNGETG' => $formData['stalngetg'][$key],
                                    'LSG_PES' => $formData['pes'][$key],
                                );

                                $this->db->insert('LISTA_SIMULADO_GABARITO',$data2);
                                //print_r($data2);
                                
                                $query = 'SELECT SQL_CACHE PLS_ID FROM PUBLICACAO_SIMULADO'
                                        .' WHERE '.$this->_pk.' = '.$id.' AND PLS_STA = 1';
                                
                                $pub = $this->db->fetchRow($query);
                                if($pub['PLS_ID'] > 0){
                                    
                                    $query = 'SELECT SQL_CACHE * FROM PUBLICACAO_SIMULADO_GABARITO '
                                        .' WHERE PSG_QST ='.$q.' AND PLS_ID = '.$pub['PLS_ID']
                                        .' AND DCP_ID = '.$formData['d'][$key];
                                    $pub2 = $this->db->fetchRow($query);
                                    if($pub2['PSG_ID'] > 0){
                                        $upd = array(
                                            'PSG_ALT' => strtoupper($formData['a'][$q.'_'.$formData['d'][$key]]),
                                            'DCP_ID'  => $formData['d'][$key],
                                            'PSG_TPO' => $formData['tpo_res'][$key],
                                            'PSG_STALNGETG' => $formData['stalngetg'][$key],
                                            'PSG_PES' => $formData['pes'][$key],
                                        );

                                        $this->db->update('PUBLICACAO_SIMULADO_GABARITO',$upd,' PSG_QST = '.$q.' AND PLS_ID = '.$pub['PLS_ID'].' AND DCP_ID = '.$formData['d'][$key]); 
                                    }else{
                                        $arr = array(
                                            'PLS_ID'  => $pub['PLS_ID'],
                                            'PSG_QST' => $q,
                                            'PSG_ALT' => strtoupper($formData['a'][$q.'_'.$formData['d'][$key]]),
                                            'DCP_ID'  => $formData['d'][$key],
                                            'PSG_TPO' => $formData['tpo_res'][$key],
                                            'PSG_STALNGETG' => $formData['stalngetg'][$key],
                                            'PSG_PES' => $formData['pes'][$key],
                                        );
                                        $this->db->insert('PUBLICACAO_SIMULADO_GABARITO',$arr);
                                        //print_r($arr);
                                    }
                                }
                            }
                        }
                    }
                    
                    $this->db->commit();
                    
                    $this->_helper->redirector('index'); 
                    
                } else {
                    echo '<script>alert("'.$msg.'");</script>';
                    $this->form->populate($formData);
                }
            } catch(Exception $ex) {
                echo '<script>alert("'.$ex->getMessage().'");</script>';
                $this->form->populate($formData);
                $this->db->rollBack();
            }
        } else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $data = $this->db->fetchRow('SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$this->_pk . ' = ' . $id);
                $this->form->populate($data);
            }
        }
    }

    public function deleteAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $msg = '';
        $id = $this->_getParam('id', 0);
        if((int) $id > 0 ) {   
            $this->db->beginTransaction();
            try {
                
                $ok = (bool) $this->db->delete('LISTA_SIMULADO_GABARITO','LTS_ID = ' . $id );
                $ok = (bool) $this->db->delete($this->_table,'LTS_ID = ' . $id );
                
                $this->db->commit();
            } catch(Exception $ex) {
                //echo getMessage();
                $ok = FALSE;
                $msg = MSG_DELETE;
                $this->db->rollBack();
            }             
        }       
        echo json_encode(array('ok' => $ok, 'msg'=> $msg));
        //$this->_helper->redirector('index');
    }
    
    public function validaencerramento($PLS_ID){
        $ok = FALSE;
        $where = ' PLS_ID = '.$PLS_ID;
        $query = 'SELECT SQL_CACHE PLS_ID, PLS_DATENC, PLS_HORENC, PLS_STA FROM PUBLICACAO_SIMULADO WHERE '.$where;
        $row = $this->db->fetchRow($query);
        
        if($row['PLS_STA'] == 3){
            $ok = TRUE;
        }
        else{
            $ok = FALSE;
        }
        
        return $ok;
    }
    
    public function buscaprovasAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $html = '<option value="">Nenhum</option>';
        $id = $this->_getParam('id', 0);
        
        if($id > 0 ) {   
            $ok = true;
            $query = 'SELECT SQL_CACHE FAP_ID,FAP_NOM FROM FACULDADE_PROVA '
                    .' WHERE FAC_ID = '.$id.' AND FAP_STA = 1 '
                    .' ORDER BY FAP_NOM';
            $result = $this->db->fetchAll($query);
            foreach($result as $row){
                $html .= '<option value="'.$row['FAP_ID'].'">'.$row['FAP_NOM'].'</option>';
            }
        }
        
        echo json_encode(array('ok' => $ok, 'html'=> $html));
    }
    
    public function montagabaritoAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $html = '';
        $id = $this->_getParam('id', 0);
        
        Zend_Loader::loadClass('dominio','library');
        
        if($id > 0 ) {   
            $ok = true;
            
            $num_qst = 1;
            $num_qst_stalngest = 0;
            $num_qst_dcp = '';
            
            $tpo = 1;
            $arr_tpo = dominio::tipoAlternativa();
            $cmb_tpo = '<select name="tpo_res[]" class="tam_med tpo_res" >';
            foreach($arr_tpo as $key => $a_tpo){
                $selected = $tpo == $key ? 'selected="selected"':'';
                $cmb_tpo .= '<option '.$selected.' value="'.$key.'">'.$a_tpo.'</option>';
            }
            $cmb_tpo .= '</select>';
            
            $query = 'SELECT SQL_CACHE DCP_ID,DCP_NOM FROM DISCIPLINA WHERE DCP_STA = 1 ORDER BY DCP_NOM';
            $res_dis = $this->db->fetchAll($query);
            
            $query = 'SELECT SQL_CACHE f.*,d.DCP_STALNGETG, d.DCP_STARED FROM FACULDADE_PROVA_DISC f, DISCIPLINA d '
                    .' WHERE f.DCP_ID = d.DCP_ID AND FAP_ID = '.$id
                    .' AND d.DCP_STARED = 0'
                    .' ORDER BY f.FPD_ID';
            $result = $this->db->fetchAll($query);
            foreach($result as $row){
                
                $cmb_dis = '<select name="d[]" class="tam_med_g dis_qst" style="display:none;"><option value="">Disciplina</option>';
                $_nome_dis = '';
                foreach($res_dis as $row_dis){
                    $selected = $row['DCP_ID'] == $row_dis['DCP_ID'] ? 'selected="selected"':'';
                    $cmb_dis .= '<option '.$selected.' value="'.$row_dis['DCP_ID'].'">'.$row_dis['DCP_NOM'].'</option>';
                    if($row['DCP_ID'] == $row_dis['DCP_ID']) $_nome_dis = $row_dis['DCP_NOM'];
                }
                $cmb_dis .= '</select>'.$_nome_dis;
                
                
                for($i=0;$i < $row['FPD_NQU'];$i++){
                    
                    // regra lingua estrangueira
                    if($row['DCP_STALNGETG'] == 1 && $i == 0){
                        
                        if($num_qst_stalngest == 0){
                            $num_qst_stalngest = $num_qst;
                        }
                        else{
                            $num_qst = $num_qst_stalngest;
                        }
                    } 
                    
                    $num_qst_dcp = '_'.$row['DCP_ID'];
                    
                    $html .= '<div class="cnt_el">';
                    $html .= '<input type="hidden" name="stalngetg[]" value="'.$row['DCP_STALNGETG'].'">';
                    $html .= '<input type="hidden" name="pes[]" value="'.$row['FPD_PES'].'">';
                    $html .= '<span class="cnt_dis">'.$cmb_tpo.'</span>';
                    $html .= '<span class="cnt_num_qst">';
                    $html .= ' <input type="text" class="num_qst" name="q[]" maxlength="3" value="'.$num_qst.'" readonly>';
                    $html .= '</span>';
                    
                    $html .= '<span class="cnt_qst_alt">';
                    
                    $arr_qst = dominio::getAlternativa($tpo);
                    if(is_array($arr_qst)){
                        foreach($arr_qst as $key => $qst){
                            $html .= '<input type="radio" id="'.$num_qst.$num_qst_dcp.''.$key.'" class="rd_qst_alt" name="a['.$num_qst.$num_qst_dcp.']" value="'.$key.'" >'; //
                            $html .= ' &nbsp; <label for="'.$num_qst.$num_qst_dcp.''.$key.'"><span class="btn_qst_alt qst'.$num_qst.'" qst="'.$num_qst.'" val="'.$key.'">'.$qst.'</span></label> &nbsp; ';
                        }
                    }else if($key_tpo == 3){
                        $html .= '<input type="text" id="'.$num_qst.''.$key.'" class="num_int numero" maxlength="3" name="a['.$num_qst.']" value="" >';
                    }
                    
                    $html .= '</span>';
                    $html .= '<span class="cnt_dis txt_dis">'.$cmb_dis.'</span>';
                    //$html .= '<span class="cnt_btn"><a href="javascript:void(0)" class="exc exc'.$num_qst.'" qst="'.$num_qst.'">Excluir</a></span>';
                    $html .= '</div>';
                    
                    $num_qst++;
                }
            }
        }
        
        echo json_encode(array('ok' => $ok, 'html'=> $html));
    }
    
    
}